const api = require('../../../api/store_api');
import { toast, log, err, get } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    item: {},
    actions: [
      {
        name: '微信支付',
        payType: 'WX_PAY',
      },
      {
        name: '积分支付',
        payType: 'INTEGRAL_PAY',
      },
    ],
    payshow: false,
    isclick: true,
    show: false,
    remark: '',
    return_show: false,
    mch: get('mch'),
    markNo: get('markNo'),
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
    });
    this.dtlorder();
  },
  onChange(event) {
    this.setData({ radio: event.detail });
  },
  onClick(event) {
    const { name } = event.currentTarget.dataset;
    this.setData({ radio: name });
  },
  async onSelect(e) {
    const { payType } = e.detail;
    const { isclick, id } = this.data;
    if (!isclick) return;
    this.setData({ isclick: false });
    wx.showLoading({ title: '支付中' });
    try {
      const memberId = get('user').id;
      if (!id || !payType) {
        throw new Error('支付信息参数不完整，请稍后重试');
      }
      const data = { ordersId: id, payType, memberId };
      const { respCode, msg, source } = await api.userpay(data);
      if (respCode === 200) {
        if (payType === 'WX_PAY') {
          const payment = JSON.parse(source);
          payment.timeStamp = payment.timeStamp.toString();
          console.log(payment);
          try {
            await new Promise((resolve, reject) => {
              wx.requestPayment({
                ...payment,
                success: res => {
                  console.log(res);
                  resolve(res);
                },
                fail: err => {
                  console.log(err);
                  reject(err);
                },
              });
            });
            this.paytoast();
          } catch (error) {
            err(error);
          }
        } else {
          this.paytoast();
        }
      } else {
        toast(msg);
      }
    } catch (error) {
      err(error);
      toast('发起支付请求失败，请稍后再试！');
      throw error;
    } finally {
      wx.hideLoading();
      this.setData({ isclick: true });
    }
  },
  paytoast() {
    toast('支付成功，即将返回订单列表');
    setTimeout(() => {
      wx.switchTab({ url: '/pages/order/order' });
    }, 1500);
  },
  async dtlorder() {
    try {
      const { id } = this.data;
      const { respCode, source } = await api.chaorders({ id });
      if (respCode === 200) {
        let item = JSON.parse(source);
        console.log(item);
        item.ordersItemBOList.forEach(e => {
          e.checkbox = false;
          e.returncount = 1;
        });
        log(item);
        const { status, returnCount, returnAmount } = item;
        if (status === 'SUCCESS' && returnCount === 0 && returnAmount === 0) {
          this.setData({ return_show: true });
        }
        this.setData({ item });
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async postpay() {
    this.setData({ payshow: true });
  },
  oncheckbox(e) {
    try {
      const { i } = e.currentTarget.dataset;
      const bool = e.detail;
      let { item } = this.data;
      item.ordersItemBOList[i].checkbox = bool;
      this.setData({ item });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  change(e) {
    try {
      const { i } = e.currentTarget.dataset;
      const count = e.detail;
      let { item } = this.data;
      item.ordersItemBOList[i].returncount = count;
      this.setData({ item });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async onreturn() {
    try {
      const ordersReturnItemBOList = this.data.item.ordersItemBOList
        .filter(e => e.checkbox)
        .map(e => ({ id: e.id, goodsCount: e.returncount }));
      if (ordersReturnItemBOList.length === 0) {
        toast('请选择需要退款的商品');
      } else {
        const data = {
          orderId: this.data.id,
          ordersReturnItemBOList,
          deskId: this.data.item.deskId,
          remark: this.data.remark,
        };
        const res = await api.payrefund(data);
        if (res.respCode === 200) {
          toast('发起退款成功，等待商家确认');
          this.setData({ show: false });
          this.dtlorder();
        } else {
          toast(res.msg);
        }
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onpayshow() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false, payshow: false });
  },
});
